package com.goudan.ojcommon.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitMqConfig {

    // 主交换机、队列、路由键
    public static final String EXCHANGE_NAME = "oj_exchange";
    public static final String QUEUE_NAME = "oj_queue";
    public static final String ROUTING_KEY = "oj_create";

    // 死信交换机、队列、路由键
    public static final String DEAD_EXCHANGE_NAME = "oj_dead_exchange";
    public static final String DEAD_QUEUE_NAME = "oj_dead_queue";
    public static final String DEAD_ROUTING_KEY = "oj_dead";

    // 主交换机
    @Bean
    public TopicExchange topicExchange() {
        return new TopicExchange(EXCHANGE_NAME);
    }

    // 死信交换机
    @Bean
    public TopicExchange deadExchange() {
        return new TopicExchange(DEAD_EXCHANGE_NAME);
    }

    // 主队列，带死信参数
    @Bean
    public Queue mainQueue() {
        Map<String, Object> args = new HashMap<>();
        args.put("x-dead-letter-exchange", DEAD_EXCHANGE_NAME);     // 绑定死信交换机
        args.put("x-dead-letter-routing-key", DEAD_ROUTING_KEY);    // 绑定死信路由键
        return new Queue(QUEUE_NAME, true, false, false, args);
    }

    // 死信队列
    @Bean
    public Queue deadQueue() {
        Map<String, Object> args = new HashMap<>();
        args.put("x-message-ttl", 3600000); // 1小时后过期
        return new Queue(DEAD_QUEUE_NAME, true, false, false, args);
    }


    // 绑定：主队列 -> 主交换机
    @Bean
    public Binding mainBinding() {
        return BindingBuilder.bind(mainQueue()).to(topicExchange()).with(ROUTING_KEY);
    }

    // 绑定：死信队列 -> 死信交换机
    @Bean
    public Binding deadBinding() {
        return BindingBuilder.bind(deadQueue()).to(deadExchange()).with(DEAD_ROUTING_KEY);
    }
}
